package com.lyubia.shop.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.lyubia.shop.api.pojo.Admin;
import com.lyubia.shop.api.service.CartService;
import com.lyubia.shop.api.vo.CartResult;
import com.lyubia.shop.api.vo.GoodsVo;
import com.lyubia.shop.common.enums.*;
import com.lyubia.shop.common.result.BaseResult;
import com.lyubia.shop.order.mapper.OrderGoodsMapper;
import com.lyubia.shop.order.mapper.OrderMapper;
import com.lyubia.shop.order.pojo.Order;
import com.lyubia.shop.order.pojo.OrderExample;
import com.lyubia.shop.order.pojo.OrderGoods;
import com.lyubia.shop.order.service.OrderService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderGoodsMapper orderGoodsMapper;

    @Value("${user.ticket}")
    private String userTicket;

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${redis.order.increment}")
    private String redisOrderIncrement;

    @Reference(version = "1.0")
    private CartService cartService;

    /**
     * 生产订单玉订单商品信息
     * @param adminId 用户id
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public BaseResult submitOrder(int adminId) {
        BaseResult baseResult = BaseResult.success("订单生成成功!");
        CartResult cartListInfo = cartService.getCartListInfo(adminId);
        if (cartListInfo.getCartList().size() <= 0) {
            baseResult.setCode(BaseResultEnum.ERROR.getCode());
            baseResult.setMsg("生成订单失败!");
            return baseResult;
        }
        //Admin admin = (Admin) redisTemplate.opsForValue().get(userTicket + ":" + adminId);
        // 构建订单信息
        Order order = new Order();
        String orderSn = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                + getRedisIncrement(redisOrderIncrement);
        order.setOrderSn(orderSn);
        //order.setAddTime(((Long) System.currentTimeMillis()).intValue());
        order.setUserId(adminId);
        order.setShippingStatus(ShipStatus.no_send.getStatus());
        order.setOrderStatus(OrderStatus.no_confirm.getStatus());
        order.setPayStatus(PayStatus.no_pay.getStatus());
        //order.setConsignee(admin.get);
        order.setGoodsPrice(cartListInfo.getTotalPrice());
        order.setTotalAmount(cartListInfo.getTotalPrice());
        int i = orderMapper.insertSelective(order);
        if (i != 1) {
            baseResult.setCode(BaseResultEnum.ERROR.getCode());
            baseResult.setMsg("生成订单失败!");
            return baseResult;
        }
        List<OrderGoods> orderGoodsList = new ArrayList<>();
        cartListInfo.getCartList()
                .forEach(GoodsVo -> {
                    OrderGoods orderGoods = new OrderGoods();
                    orderGoods.setOrderId(order.getOrderId());
                    orderGoods.setGoodsId(GoodsVo.getGoodsId());
                    orderGoods.setGoodsName(GoodsVo.getGoodsName());
                    orderGoods.setGoodsPrice(GoodsVo.getMarketPrice());
                    orderGoods.setGoodsNum(GoodsVo.getGoodsNum().shortValue());
                    orderGoods.setPromType(PromTypeStatus.normal.getStatus());
                    orderGoods.setIsSend(SendStatus.no_pay.getStatus());
                    orderGoodsList.add(orderGoods);
                });
        i = orderGoodsMapper.insertOrderGoodsBatch(orderGoodsList);
        if (i != orderGoodsList.size()) {
            baseResult.setCode(BaseResultEnum.ERROR.getCode());
            baseResult.setMsg("生成订单失败!");
            return baseResult;
        }
        cartService.clearCart(adminId);
        Map<String, Object> map = new HashMap<>();
        map.put("orderSn",order.getOrderSn());
        map.put("totalAmount", order.getTotalAmount());

        baseResult.setObj(map);
        return baseResult;
    }

    @Override
    public Order selectOrderByOrderSn(String orderSn) {
        OrderExample example = new OrderExample();
        example.createCriteria().andOrderSnEqualTo(orderSn);
        List<Order> orders = orderMapper.selectByExample(example);
        if (CollUtil.isEmpty(orders))
            return null;
        return orders.get(0);
    }


    /**
     * 生产redis自增key
     * @return
     */
    private Long getRedisIncrement(String key) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key,
                redisTemplate.getConnectionFactory());
        return redisAtomicLong.getAndIncrement();
    }

}
